package com.mining.app.zxing.decoding;


import java.util.Hashtable;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.mining.app.zxing.camera.IMECameraManager;
import com.mining.app.zxing.camera.PlanarYUVLuminanceSource;
import qs.openxt.libs.R;
import qs.openxt.libs.qrcode.QrcodeCaptureActivity;

final class IMEDecodeHandler extends Handler {

	private final QrcodeCaptureActivity activity;
	private final MultiFormatReader multiFormatReader;

	public IMEDecodeHandler(QrcodeCaptureActivity activity,
			Hashtable<DecodeHintType, Object> hints) {
		multiFormatReader = new MultiFormatReader();
		multiFormatReader.setHints(hints);
		this.activity = activity;
	}

	@Override
	public void handleMessage(Message message) {
		if (message.what == R.id.qrcode_decode) {
			decode((byte[]) message.obj, message.arg1, message.arg2);
		} else if (message.what == R.id.qrcode_quit) {
			Looper.myLooper().quit();
		}
	}

	private void decode(byte[] data, int width, int height) {
		Result rawResult = null;

		byte[] rotatedData = new byte[data.length];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++)
				rotatedData[x * height + height - y - 1] = data[x + y * width];
		}
		int tmp = width; // Here we are swapping, that's the difference to #11
		width = height;
		height = tmp;

		PlanarYUVLuminanceSource source = IMECameraManager.get()
				.buildLuminanceSource(rotatedData, width, height);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		try {
			rawResult = multiFormatReader.decodeWithState(bitmap);
		} catch (Exception re) {
		} finally {
			multiFormatReader.reset();
		}

		if (rawResult != null) {
			Message message = Message.obtain(activity.getHandler(),
					R.id.qrcode_decode_succeeded, rawResult);
			Bundle bundle = new Bundle();
			bundle.putParcelable(IMEDecodeThread.BARCODE_BITMAP,
					source.renderCroppedGreyscaleBitmap());
			message.setData(bundle);
			message.sendToTarget();
		} else {
			Message message = Message.obtain(activity.getHandler(),
					R.id.qrcode_decode_failed);
			message.sendToTarget();
		}
	}

}
